import React, {Component} from 'react';
import {Button, Form, Row, Col, DatePicker, Table, Pagination, Input} from 'antd';
import moment from 'moment';
import {statistics, excel} from "../value";
import app from '../AppMethod';
import {config} from "../config";
import {Consumer} from "../store";
import '../css/orderAppointment.css';
import phone from '../image/phone1.png';
import arrow from '../image/arrow.png';

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;

class orderInStore extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            pagination: {
                current: 0,
                total: 0,
                pagination: 0
            },
            allPage: 0,
            currentOrderType: 1,
            orderData: [
                {
                    orderNo: '01',
                    orderId: '00001',
                    orderAllPrice: '40',
                    orderNumber: '0001',
                    orderNumber1: '20181212121211',
                    orderTime: '2018-12-12 12:12',
                    orderStatus: 0,
                    customerPhone: '15637728986',
                    orderName: '我心飞翔',
                    orderRemark: '请加汤',
                    orderGoodNum: '2',
                    show: false,
                    orderGoodList: [
                        {
                            goodName: '手撕鸡腿饭',
                            goodPrice: '20',
                            goodNum: '1',
                            goodAllPrice: '20'
                        },
                        {
                            goodName: '排骨蒸饭',
                            goodPrice: '20',
                            goodNum: '1',
                            goodAllPrice: '20'
                        },
                    ]
                },
                {
                    orderNo: '02',
                    orderId: '00002',
                    orderAllPrice: '60',
                    orderNumber: '0002',
                    orderNumber1: '20181212121212',
                    orderTime: '2018-12-12 12:12',
                    orderStatus: 1,
                    customerPhone: '15637728986',
                    orderName: '我心飞翔',
                    orderRemark: '请加汤',
                    orderGoodNum: '2',
                    show: false,
                    orderGoodList: [
                        {
                            goodName: '手撕鸡腿饭',
                            goodPrice: '30',
                            goodNum: '2',
                            goodAllPrice: '60'
                        },
                    ]
                }
            ],
            show: false
        }
    };

    render() {
        const {currentOrderType, show} = this.state;
        return (
            <div style={{height: '100%'}}>
                <Row className="orderStatisticHeader">
                    订单管理/预约订单
                </Row>
                <Row style={{display: 'flex', marginTop: 15}}>
                    <div className={`orderStatisticBtnItem ${currentOrderType == 1 ? 'active' : ''}`}
                         onClick={() => this.handleChooseOrderType(1)}>全部订单
                    </div>
                    <div className={`orderStatisticBtnItem ${currentOrderType == 2 ? 'active' : ''}`}
                         onClick={() => this.handleChooseOrderType(2)}>待确认
                    </div>
                    <div className={`orderStatisticBtnItem ${currentOrderType == 3 ? 'active' : ''}`}
                         onClick={() => this.handleChooseOrderType(3)}>已确认
                    </div>
                    <div className={`orderStatisticBtnItem ${currentOrderType == 4 ? 'active' : ''}`}
                         onClick={() => this.handleChooseOrderType(4)}>已完成
                    </div>
                    <div className={`orderStatisticBtnItem ${currentOrderType == 5 ? 'active' : ''}`}
                         onClick={() => this.handleChooseOrderType(5)}>已关闭
                    </div>
                </Row>
                <Row style={{marginTop: 25}}>
                    <SearchLists
                        clickSearch={(value) => {
                            this.handleGetSearch(value)
                        }}
                        handleReset={() => this.handleReset()}
                        handleExport={(values) => this.handleExport(values)}
                    >
                    </SearchLists>
                </Row>
                <div className="orderStatisticTableContainer">
                    <Row className="orderTakeoutContainer">
                        {
                            this.state.orderData.length > 0 ?
                                this.state.orderData.map((item, index) => {
                                    return (
                                        <OrderItem key={index} data={item}
                                                   handleChangeImg={(id) => this.handleChangeImg(id)}/>
                                    )
                                }) : ''
                        }
                    </Row>
                    <Row style={{marginTop: '20px'}}>
                        <Col span={12} style={{fontSize: '15px'}}>
                            共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                            页
                        </Col>
                        <Col span={12} style={{textAlign: 'right'}}>
                            <Pagination {...this.state.pagination} hideOnSinglePage={false}
                                        onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}/>
                        </Col>
                    </Row>
                </div>
            </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "订单数据统计"});
        let date_end = moment(new Date()).format('YYYY-MM-DD');
        let date_start = app.getBeforeDate(4);
        let data = {page: 1, size: 5, date_start: date_start, date_end: date_end};
        //this.handleGetOrderList(data);
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    };

    /**
     * 处理当担状态选择变化事件
     * @param index
     */
    handleChooseOrderType(index) {
        this.setState({currentOrderType: index});
    }

    handleChangeImg(id) {
        let orderData = this.state.orderData;
        for (let i = 0; i < orderData.length; i++) {
            if (id == orderData[i].orderId) {
                orderData[i].show = !orderData[i].show;
            }
        }
        this.setState({orderData: orderData});
    }

    /**
     * 获取订单数据列表
     * @param data
     */
    handleGetOrderList(data = {page: 1, size: 5, date_start: '2018-06-01', date_end: '2018-06-05'}) {
        this.setState({loading: true});
        app.post(statistics.TOTAL_OUTPUTSTATISTICS, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                this.setState({allPage, pagination});
                let employeeData = result.data.dataSet;
                let employeeData1 = [];
                let employeeData2 = [
                    ['time', '下单数', '未配货', '已配货', '配送中', '已配送'],
                ];
                for (let i = 0; i < employeeData.length; i++) {
                    employeeData[i].date_id = employeeData[i].date_id == null ? '' : moment(employeeData[i].date_id).format('YYYY-MM-DD');
                    employeeData1 = [];
                    employeeData1.push(employeeData[i].date_id);
                    employeeData1.push(employeeData[i].total_output);
                    employeeData1.push(employeeData[i].total_unpick);
                    employeeData1.push(employeeData[i].total_pick);
                    employeeData1.push(employeeData[i].total_send);
                    employeeData1.push(employeeData[i].total_finish);
                    employeeData2.push(employeeData1);
                }
                let rawMill = this.state.rawMill;
                rawMill.dataset.source = employeeData2;
                this.setState({rawMill, data: employeeData, loading: false});
            } else {
                let rawMill = this.state.rawMill;
                rawMill.dataset.source = [['time', '下单数', '未配货', '已配货', '配送中', '已配送']];
                this.setState({rawMill, data: [], loading: false});
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({allPage, pagination});
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 根据条件搜索订单列表
     * @param value
     */
    handleGetSearch(value) {
        let times = value.date;
        let date_start = undefined;
        let date_end = undefined;
        if (times != undefined && times.length > 0) {
            date_start = moment(times[0]._d).format('YYYY-MM-DD');
            date_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let tempData = {
            date_start: date_start,
            date_end: date_end
        };
        this.setState({searchData: tempData});
        let searchData = tempData;
        searchData.page = 1;
        searchData.size = 5;
        this.handleGetOrderList(searchData);
    };

    /**
     * 处理重置事件
     */
    handleReset() {
        this.setState({searchData: {}});
        let date_end = moment(new Date()).format('YYYY-MM-DD');
        let date_start = app.getBeforeDate(4);
        let data = {page: 1, size: 5, date_start: date_start, date_end: date_end};
        this.handleGetOrderList(data);
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleGetOrderList(data);
    };

    /**
     * 处理导出Excel事件
     * @param value
     */
    handleExport(value) {
        let times = value.date;
        let date_start = undefined;
        let date_end = undefined;
        if (times != undefined && times.length > 0) {
            date_start = moment(times[0]._d).format('YYYY-MM-DD');
            date_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let tempData = {
            date_start: date_start,
            date_end: date_end
        };
        let params = app.getParams(tempData);
        if (params.length > 0) {
            window.location.href = config.serverUrl + excel.EXPORT_OUTPUTSTATISTICS + '?' + params;
        } else {
            app.alert('请选择时间范围', 'error', 3);
        }
    }
};

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentTime: 1
        }
    };

    formItemLayout = {
        labelCol: {span: 6},
        wrapperCol: {span: 14},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const {currentTime} = this.state;
        return (
            <Row>
                <Form className="login-form">
                    <Col span={5}>
                        <FormItem>
                            {
                                getFieldDecorator('date')(
                                    <Input placeholder="订单号/客户名/联系方式"/>
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col offset={1} span={6}>
                        <FormItem>
                            {
                                getFieldDecorator('date')(
                                    <RangePicker
                                        ranges={{
                                            Today: [moment(), moment()],
                                            'This Month': [moment(), moment().endOf('month')]
                                        }}
                                        format="YYYY/MM/DD"
                                        onChange={(dates, dateStrings) => this.handleOnChange(dates, dateStrings)}
                                    />
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col offset={1} span={11} style={{float: 'right', display: 'flex', marginTop: 4}}>
                        <Button type="primary"
                                onClick={() => this.handleSearchComplain()}
                        >
                            搜索
                        </Button>
                        <div className={`orderStatisticBtnItem ${currentTime == 1 ? 'active' : ''}`}
                             onClick={() => this.handleChooseTime(1)}>今天
                        </div>
                        <div className={`orderStatisticBtnItem ${currentTime == 2 ? 'active' : ''}`}
                             onClick={() => this.handleChooseTime(2)}>昨天
                        </div>
                        <div className={`orderStatisticBtnItem ${currentTime == 3 ? 'active' : ''}`}
                             onClick={() => this.handleChooseTime(3)}>近七天
                        </div>
                        <div className={`orderStatisticBtnItem ${currentTime == 4 ? 'active' : ''}`}
                             onClick={() => this.handleChooseTime(4)}>本月
                        </div>
                    </Col>
                </Form>
            </Row>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取搜索条件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.handleReset();
    };

    /**
     * 获取导出Excel条件
     */
    handleExport() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.handleExport(values);
            }
        })
    };

    /**
     * 处理日期选择框变化事件
     */
    handleOnChange(dates, dateStrings) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.date = dates;
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理时间按钮点击事件
     * @param index
     */
    handleChooseTime(index) {
        this.setState({currentTime: index});
    }
}

class OrderItem extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    render() {
        const {
            orderNo, orderId, orderAllPrice, orderNumber, orderTime, customerPhone, orderStatus, orderName, orderRemark, orderGoodNum,
            show, orderGoodList, orderNumber1
        } = this.props.data;
        let orderStatusText = '';
        if (orderStatus == 0) {
            orderStatusText = '待确认';
        } else if (orderStatus == 1) {
            orderStatusText = '已确认';
        } else if (orderStatus == 2) {
            orderStatusText = '已完成';
        } else if (orderStatus == -1) {
            orderStatusText = '已关闭';
        }
        return (
            <div className="orderTakeoutItem">
                <div className="orderAppointmentItemHeader">
                    <div className="orderTakeoutItemHeaderSharp">
                        #<span style={{marginLeft: 3}}>{orderNo}</span>
                    </div>
                    <div className="orderTakeoutItemHeaderPrint">
                        <Button className={'orderTakeoutItemHeaderPrintBtn'} type="danger" ghost>打印</Button>
                    </div>
                    <div className="orderAppointmentItemHeaderOrderStatus">
                        {
                            orderStatus == 1 || orderStatus == 2 ?
                                <span>{orderStatusText}</span> : ''
                        }
                        {
                            orderStatus == 0 ?
                                <span style={{color: '#FF3300'}}>{orderStatusText}</span> : ''
                        }
                        {
                            orderStatus == -1 ?
                                <span style={{color: '#999'}}>{orderStatusText}</span> : ''
                        }
                    </div>
                </div>
                <div className="orderTakeoutItemName">
                    <span style={{width: 250}}>{orderName}</span>
                    <div className="orderTakeoutItemCustomerInfoPhone">
                        <span style={{marginLeft: 15}}><img src={phone}/></span>
                        <span style={{
                            color: 'rgb(0, 102, 255)',
                            fontWeight: 'normal',
                            fontSize: 14,
                            marginLeft: 3
                        }}>{customerPhone}</span>
                    </div>
                    <div className="orderInStoreItemCloseBtn">
                        {
                            orderStatus == 0 ?
                                <div className="button">确认</div> : ''
                        }
                        {
                            orderStatus == 1 ?
                                <div className="button">取消</div> : ''
                        }
                    </div>
                </div>
                <div className="orderTakeoutItemOrderRemark">
                    备注：{orderRemark}
                </div>
                <div className="orderAppointmentItemTimeContainer">
                    <div className="orderAppointmentItemTimeContainerText">预约时间</div>
                    <div className="orderAppointmentItemTimeContainerInfo">
                        <div className="TimeContainerInfoAppointmentTime">预约时间：2018-12-12 14：20</div>
                        <div className="TimeContainerInfoPeople">预约人数：4</div>
                        <div className="TimeContainerInfoAllPrice">订单总额：100</div>
                        <div className="TimeContainerInfoOrderNumber">预约单号：20181212121212</div>
                        <div className="TimeContainerInfoOrderTime">下单时间：2018-12-12 12:12</div>
                    </div>
                </div>
                {
                    orderGoodList&&orderGoodList.length>0?
                        <div className="orderTakeoutItemGoodInfo">
                            <div className="orderTakeoutItemGoodInfoText">
                                商品信息
                            </div>
                            <div className="orderTakeoutItemGoodInfoDetail">
                                <div className="orderInStoreItemGoodNum" onClick={() => this.handleChangeImg(orderId)}>
                                    <div className="orderInStoreItemGoodNumText">商品总数：{orderGoodNum}</div>
                                    <div className="orderInStoreItemGoodNumber">订单号：{orderNumber1}</div>
                                    <div className="orderInStoreItemGoodNumImg active">
                                        <img className={`orderInStoreItemGoodNumImg_img ${show ? 'active' : ''}`}
                                             src={arrow}/>
                                    </div>
                                </div>
                                <div className={`orderTakeoutItemGoodList ${show ? 'active' : ''}`}>
                                    {
                                        orderGoodList && orderGoodList.length > 0 ?
                                            orderGoodList.map((item, index) => {
                                                return (
                                                    <div className="orderTakeoutItemGoodListItem" key={index}>
                                                        <div className="orderTakeoutItemGoodListItemName">{item.goodName}</div>
                                                        <div className="orderTakeoutItemGoodListItemPrice">
                                                            ￥{item.goodPrice}</div>
                                                        <div className="orderTakeoutItemGoodListItemNum">x{item.goodNum}</div>
                                                        <div className="orderTakeoutItemGoodListItemAllPrice">
                                                            ￥{item.goodAllPrice}</div>
                                                    </div>
                                                )
                                            }) : ''
                                    }
                                </div>
                            </div>
                        </div>:''
                }
            </div>
        )
    };

    /**
     * 处理商品列表的隐藏与显示
     * @param id
     */
    handleChangeImg(id) {
        this.props.handleChangeImg(id);
    }
}

const SearchLists = Form.create()(SearchList);
const OrderInStores = Form.create()(orderInStore);
export default prop => (
    <Consumer>
        {
            props => (
                <OrderInStores {...prop} {...props}/>
            )
        }
    </Consumer>
);